#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
int thickets=100;//100张票
//thickets--表示抢票
pthread_mutex_t lock;//线程共用一个互斥锁
void* Routine(void* arg)
{
    while(1)
    {
        pthread_mutex_lock(&lock);
        if(thickets>0)
        {
            usleep(100000);//抢票时间
            printf("%s get a thickets, now thickets' number:%d\n",(char*)arg,--thickets);
            pthread_mutex_unlock(&lock);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            break;
        }
        usleep(100000);
    }
    return NULL;
}

int main()
{
    pthread_mutex_init(&lock,NULL);
    pthread_t tid1,tid2,tid3;
    pthread_create(&tid1,NULL,Routine,(void*)"thread 1");
    pthread_create(&tid2,NULL,Routine,(void*)"thread 2");
    pthread_create(&tid3,NULL,Routine,(void*)"thread 3");

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);
    pthread_mutex_destroy(&lock);
    return 0;
}
